package com.hunau.cxb.service.impl;

import com.hunau.cxb.dao.AccountDao;
import com.hunau.cxb.dao.BookDao;
import com.hunau.cxb.dao.BookStockDao;
import com.hunau.cxb.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author hb
 * @create 2020-03-22 10:45
 */

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;

    @Autowired
    private AccountDao accountDao;

    @Autowired
    private BookStockDao bookStockDao;

      @Override
    public void buyBook(String isbn, String username, int nums) throws Exception {
        //1.查询书籍的库存
        int stock = bookStockDao.queryByIsbn(isbn);
        //2. 判定是否符合要求
        if (stock < nums) {
            throw new RuntimeException("库存不够");
        }
        //3. 计算金额
        double price = bookDao.queryPrice(isbn);
        double amount = price * nums;
        //4. 判定余额是否满足要求
        double balance = accountDao.queryBalance(username);
        if (amount > balance) {
            throw new RuntimeException("余额不足");
        }
        //5.更新库存
        bookStockDao.updateStock(isbn, nums);

         if(2>1){
             throw new Exception("突然冒出的问题。");
         }


        //6.更新余额
        accountDao.updateBalance(username, amount);
    }
}
